import { getUrlParam } from "@/utils/getUrlData";
import { message } from "antd";
import { API_QUERY } from ".";


// 获取中文名称
function getName(str) {
    switch (str) {
        case "allRisk": return "全险种";
        case "carRisk": return "车险";
        case "heaRisk": return "意健险";
        case "proRisk": return "财产险";
        case "othRisk": return "其他险种";
        case "eqRisk": return "地震险";
        default:
            return str;
    }
}

// 传入数组，返回数组，把数组中每个item的value整型值换成占比
const getProVal = ({ list = [] }) => {
    var array = [];
    // 求和
    function getSum() {
        var n = 0;
        for (var i = 0; i < list.length; i++) {
            n += Number(list[i].value)
        }
        return n;
    }
    var sum = getSum()
    list.forEach(item => {
        var value = item.value[0];
        array.push({
            ...item,
            value: Number(((value / sum) * 100).toFixed(2))
        })
    })
    return array;
}



// 一个函数，传入数组对象，把allRisk等转换成约定的中文名称（全险种，车险等），或取全险种的值
function getDetailData({ list = [], type = "allRisk", toFixed = false }) {
    // type 默认是这个函数是取allRisk的value值
    // toFixed 默认不保留2位小数
    // list 传入的数组数据
    let sum = 0;
    let array = [];
    var reg = /全险种|allRisk/;
    var childrenList = list.filter(item => reg.test(item.name) === false);//过滤掉全险种
    if (list.length === 0) {
        if (type === "allRisk") {
            return sum;
        }
        return array;
    }
    list.forEach((item) => {
        if (reg.test(item.name)) {
            sum = Number(item.value || 0);
        }

    })

    childrenList.forEach(item => {
        array.push({
            title: getName(item.name),
            value: toFixed ? (Number(item.value)).toFixed(2) : Number(item.value)
        })
    })

    if (type === "allRisk") {
        if (toFixed) {
            return sum.toFixed(2);
        }
        return sum;
    }
    return array;

}

const { http } = require("@/utils")

const getState = async ({ apiUrl, moduleName, condition, state, setState, setLoading, setMessage = () => { }, nameList = [] }) => {
    try {

        if (setLoading) { setLoading(true) }
        const res = await http.post(apiUrl ? apiUrl : API_QUERY, {
            moduleName: moduleName,//模块名（生产不需要这个参数）
            ...condition,// object,内含其他查询条件
        })

        if (res.responseCode !== "0000") {
            // message.error(`${res.responseMsg}`)
            setMessage(res.responseMsg)
            return;
        }
        if (res?.data?.detailData?.length === 0) {
            setMessage("未查询到数据")
        }




        // 圆圈图：适用模块（客户分布、
        const fun1 = (res) => {
            console.log(res);
            const { detailData = [] } = res?.data;
            const data = getProVal({ list: detailData })
            setState({
                data: [...data]
            })
        }

        // 扇形图：适用模块（线上线下服务率、沟通时间偏好、沟通方式偏好
        const fun2 = (res) => {
            const { detailData = [] } = res?.data;
            setState({
                data: [...detailData]
            })
        }

        // 拆线图|柱形图：适用模块（历年来电次数、驾驶行为统计、客户赔款趋势、客户赔款趋势、历年风险数量
        const fun3 = (res) => {
            const { detailData = [], dateList = [] } = res?.data;
            setState({
                data: [...detailData],
                dayList: [...dateList]
            })
        }

        // 横向渐变条：适用模块（服务关注情况、各险种出险次数、各险种出险次数
        const fun4 = (res) => {
            const { detailData = [], dateList = [] } = res?.data;
            setState({
                data: [...detailData]
            })
        }

        // 大数据模块：适用模块（赔付信息
        const fun5 = (res) => {

            const defaultList = [{
                name: "allRisk",
                value: 0,
                statValue: 0
            },
            {
                name: "carRisk",
                value: 0,
                statValue: 0
            },
            {
                name: "heaRisk",
                value: 0,
                statValue: 0
            },
            {
                name: "proRisk",
                value: 0,
                statValue: 0
            },
            {
                name: "othRisk",
                value: 0,
                statValue: 0
            },
            {
                name: "eqRisk",
                value: 0,
                statValue: 0
            }]
            const { detailData = [] } = res?.data;
            console.log(detailData)
            console.log(
                {
                    value: getDetailData({ list: res?.data?.detailData || [], toFixed: state.toFixed }),
                    childrenData: getDetailData({ list: detailData.length > 0 ? detailData : defaultList, type: "list", toFixed: state.toFixed })
                }
            )

            setState({
                ...state,
                value: getDetailData({ list: res?.data?.detailData || [], toFixed: state.toFixed }),
                childrenData: getDetailData({ list: detailData.length > 0 ? detailData : defaultList, type: "list", toFixed: state.toFixed })
            })
        }

        // 大数据模块：适用反洗钱重点信息模块
        const fun6 = (res) => {
            let { detailData = [] } = res?.data;
            let data = [];
            if (detailData.length === 0) {
                return;
            }
            detailData.forEach((item, i) => {
                var obj = state[i];
                data.push(Object.assign(obj, { ...item }))
            })
            setState([...data])
        }



        //  投保情况统计的特殊计算处理 要转格式 后端返回格式和前端需要的不一样
        const fun9 = (res) => {
            const { detailData = [] } = res.data;
            if (detailData.length === 0) {
                setState([
                    {
                        name: "全险种",
                        data: [
                            // { name: "男性", value: [0] },
                            // { name: "女性", value: [0] },
                            // { name: "未知", value: [0] },
                        ],
                    },
                    {
                        name: "车险",
                        data: [],
                    },
                    {
                        name: "意见险",
                        data: [],
                    },
                    { name: "财产险", data: [] },
                ])
                return;
            }
            console.log("拿到的数据：\n", detailData)
            var tempList = [];
            detailData.forEach(item => {
                var obj = {};
                obj.name = item.name;
                var data = [];
                var valList = item.value;
                valList.forEach((val, index) => {
                    data.push({
                        name: nameList[index],
                        value: [val]
                    })
                })
                obj.data = data
                tempList.push(obj)
            })
            console.log("tempList", tempList)
            setState(tempList)
        }
        // 基本信息年龄分布, 
        const fun10 = ({ res, type = "array" }) => {
            const { detailData = [] } = res.data;
            if (detailData.length === 0) {
                setState([
                    {
                        name: "全险种",
                        data: [
                            // {
                            //     name: "20岁以下",
                            //     value: '0%',
                            //     statValue: 0
                            // }
                        ]
                    },
                    {
                        name: "车险",
                        data: [
                            // {
                            //     name: "20岁以下",
                            //     value: '0%',
                            //     statValue: 0
                            // }
                        ]
                    },
                    {
                        name: "意健险",
                        data: [
                            // {
                            //     name: "20岁以下",
                            //     value: '0%',
                            //     statValue: 0
                            // }
                        ]
                    },
                    {
                        name: "财产险",
                        data: [
                            // {
                            //     name: "20岁以下",
                            //     value: '0%',
                            //     statValue: 0
                            // }
                        ]
                    },
                ])
                return;
            }
            console.log("基本信息年龄分布的数据", detailData)
            var tempList = [];
            detailData.forEach(item => {
                var obj = {};
                obj.name = item.name;
                var data = [];
                var valList = item.value;
                var statList = item.statValue
                valList.forEach((val, index) => {
                    data.push({
                        name: nameList[index],
                        value: val,
                        statValue: statList[index]
                    })
                })
                obj.data = data
                tempList.push(obj)
            })
            console.log("tempList", tempList)
            setState(tempList)
        }


        const fun11 = (res) => {
            console.log("地图的数据", res.data.detailData);
            const { detailData } = res.data;
            setState([...detailData])
        }

        const { cType } = condition;
        // 根据传入的ctype值以不同方式处理数据
        switch (cType) {
            // 综合指标
            case "synttotalNum": fun3(res); break;//累计客户数量
            case "syntinsNum": fun3(res); break;//在保客户数量
            case "syntcustIdNum": fun4(res); break;//    投保情况统计
            case "syntcustRetention": fun4(res); break;//    客户留存率
            case "syntriskDistribution": fun4(res); break;//    险种分布情况
            case "syntlostCust": fun3(res); break;//客户流失统计 
            case "syntsubsidiary": fun4(res); break;//   子机构客户量统计
            case "syntvasUsage": fun3(res); break;//    增值服务使用情况
            case "syntbusinessOrigin": fun4(res); break;//业务来源分布
            case "syntapplyUsage": fun9(res); break;//投保情况统计
            case "syntdamageNum": fun9(res); break;//出险情况统计


            // 基本指标
            case "baseAge": fun10({ res, type: "string" }); break;//客户性别分布
            case "baseGender": fun9(res); break;//客户性别分布
            case "baseNationality": fun4(res); break;//国籍分布
            case "baseCertType": fun4(res); break;//证件类型分布
            case "baseCertValidity": fun2(res); break;//证件有效期分布
            case "baseOperator": fun3(res); break;//运营商统计
            case "baseFamilyNum": fun4(res); break;//家庭成员数量分布
            case "baseChildRelation": fun4(res); break;//子女数量分布
            case "baseParentRelation": fun4(res); break;//父母数量分布
            case "baseArea": fun11(res); break;//地图


            // case "education": fun2(res); break;//学历 
            // case "mar": fun4(res); break;//婚姻
            // case "mediInsure": fun4(res); break;//医保


            // 车辆指标
            case "carCount": fun2(res); break;//客户车辆数量分布
            case "carAge": fun3(res); break;//客户车龄统计
            case "countryNature": fun2(res); break;//车辆国别统计
            case "secondHandCarFlag": fun2(res); break;//二手车分布
            case "usenatureCode": fun2(res); break;//车辆使用性质分布
            case "origincarPrice": fun3(res); break;//客户车龄统计
            case "carType": fun2(res); break;//车辆国别统计
            case "brand": fun2(res); break;//家庭成员数量分布


            // 客户行为
            case "actOnOffLine": fun2(res); break;
            case "actOnLine": fun1(res); break;
            case "actTelegram": fun3(res); break;
            case "actCareService": fun4(res); break;
            case "actNps": fun2(res); break;
            case "actDrivingBehavior": fun3(res); break;
            case "actPrefTime": fun2(res); break;
            case "actPrefMethod": fun2(res); break;

            // 承保指标
            case "insNum": fun4(res); break;
            case "insAmt": fun5(res); break;//累计保费
            case "insAvgAmt": fun5(res); break;//人均保费
            case "insCancel": fun5(res); break;//退保客户数
            case "plyNum": fun5(res); break;//获取客单量
            case "riskNum": fun2(res); break;
            case "keepInsNum": fun4(res); break;
            case "insAvgAmtTrend": fun3(res); break;
            case "totInsNum": fun4(res); break;
            case "insPlyNumTrend": fun3(res); break;
            case "insSurrenderNumTrend": fun3(res); break;

            // 理赔指标
            case "clmriskNum": fun4(res); break;
            case "clmreparation": fun5(res); break;
            case "clmcaseNum": fun5(res); break;//赔款案件数量
            case "clmrejectNum": fun5(res); break;
            case "clmcheatNum": fun5(res); break;//欺诈客户数
            case "clmlossNum": fun5(res); break;//全损案件数
            case "clmavsCaseNum": fun5(res); break;
            case "clmriskNumPercent": fun4(res); break;
            case "clmreparationTrend": fun3(res); break; //客户赔款趋势 和上面的重复了，待修改
            case "clmriskNumTrend": fun3(res); break;//客户出险趋势 和上面的重复了，待修改
            case "clmtotalNum": fun4(res); break;//累计出险次数分布
            case "clmcontinuityNum": fun4(res); break;//连续出险人数分布
            case "clmcaseNumTrend": fun3(res); break;//赔款案件数量趋势 趋势和上面的重复了，待修改
            case "clmrejectNumTrend": fun3(res); break;//拒赔客户数趋势和上面的重复了，待修改

            // 反洗钱指标
            case "fxqRisk": fun3(res); break;//历年风险数量
            case "fxqBlackFlag": fun3(res); break;//人员性质统计
            case "fxqSuspicious": fun3(res); break;//可疑交易趋势
            case "fxqLargeAmount": fun3(res); break;//大额交易趋势
            case "fxqState": fun6(res); break;//反洗钱重点数据模块
            default:


        }



    } catch (error) {
        console.log("catch:", error)
        // message.error(`网络连接失败`)
        setMessage("网络连接失败")
        // 做异常或者失败处理，应该在单模块显示网络连接失败，而不要弹消息，不然太多弹窗
    } finally {
        if (setLoading) { setLoading(false) }
    }
}

export default getState;